/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package programmer;

import java.io.File;
import java.util.ArrayList;
import ssl.*;

/**
 *
 * @author benjamincurrie
 */
public class Programmer {

	private static JavaRunCommand comm = new JavaRunCommand(); // For running terminal commands
	private static File dir; //The directory containing the programmers
	private static File tmp = new File("tmp"); //The temporary directory for final product
	private static String separator = File.separator;

	// SSL Info
	private static String linkBrokerIP = "localhost";
	private static String port = "6969";

    /**
     * @param args the command line arguments
     */
    public Programmer(String directory) {
        dir = new File(directory);
		
		if (!dir.isDirectory()) {
			System.out.println("Incorrect directory provided");
			return;
		}
		
		if (!tmp.isDirectory()) {
			tmp.mkdir();
		}

		// Clean out the tmp directory
		comm.run("rm -r " + tmp + separator + "*");
        
		//BEGIN!

		//Compile all c to objects
		ArrayList objects = new ArrayList();

		for(File file : dir.listFiles()) {
			if(Filename.checkExtension(file, "c")) {
				objects.add(compile(file));
			}
		}

		//Link all objects together
		File final_product = new File(tmp + separator + "PROGRAM");
		String link_command = "ld -r -o " + final_product;
		for(Object file : objects) {
			link_command = link_command + " " +file;
		}
		comm.run(link_command);
		for(Object file : objects) {
			comm.run("rm " + file);
		}

		//Encrypt the link requests
		for(File file : dir.listFiles()) {
			if(Filename.checkExtension(file, "lnk")) {
				String key = dir + separator + Filename.fileName(file) + ".k";
				encrypt(file, key, tmp);
			}
		}

		//Archive the tmp directory files for sending
		//comm.run("cd "+tmp+";"+"zip program.zip -m *");

		send(); //The ssl magic!!
    }

	private static String compile(File file) {
		String name = Filename.fileName(file);
		name = dir + separator + name+".o";
		comm.run("gcc -c -o " + name + " " + file);
		return name;
	}

	private static void encrypt(File file, String key, File destination) {
		Encryption encryption = new Encryption(key);
		String name = destination + separator + Filename.fileName(file);
        encryption.GenerateSignature(file.getAbsolutePath(), name + ".sig", name + ".k");
        encryption.encrypt(file.getAbsolutePath(), name + ".en");
    }

	private static void send() {

		// Initialize server with path to files, realistically this should be an RMI, or additionally
		final String[] ServerInfo = {port, tmp.getAbsolutePath(), "TLS"};
        Thread serverThread = new Thread() {
			@Override
            public void run() {
                try {
					ClassFileServer.main(ServerInfo);
				} catch (Exception e) {
					e.printStackTrace();
				}
            }
        };

		// Initialize client asking for final product
		final String[] ClientInfo = {linkBrokerIP, port, "FINAL"};
        Thread clientThread = new Thread() {
			@Override
            public void run() {
                try {
					Client.main(ClientInfo);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
        };

		serverThread.start();
		clientThread.start();

		/*
		 * Last resort we cp the files
		 */
		//String destination = dir.getAbsolutePath().replaceAll("Programmer", "LinkBroker/tmp/");
		//comm.run("cp -r " + tmp + " " + destination);
    }
	
}
